package com.example.universitylibraryback.pipeline.filter;

import com.example.universitylibraryback.pipeline.BorrowContext;
import com.example.universitylibraryback.pipeline.Filter;
import java.util.concurrent.BlockingQueue;

/**
 * 借阅请求解析过滤器
 * 负责解析原始输入为读者证号和图书ID
 */
public class BorrowRequestParserFilter implements Filter<BorrowContext>, Runnable {
    private BlockingQueue<BorrowContext> inputQueue;
    private BlockingQueue<BorrowContext> outputQueue;

    @Override
    public void process(BlockingQueue<BorrowContext> inputQueue, BlockingQueue<BorrowContext> outputQueue) throws InterruptedException {
        this.inputQueue = inputQueue;
        this.outputQueue = outputQueue;
        new Thread(this).start();
    }

    @Override
    public void run() {
        try {
            while (!Thread.currentThread().isInterrupted()) {
                BorrowContext context = inputQueue.take();
                String[] parts = context.getRawInput().split(",");
                if (parts.length != 2) {
                    context.setValid(false);
                    context.setErrorMsg("输入格式错误，应为'读者证号,图书ID'");
                } else {
                    context.setReaderId(parts[0].trim());
                    context.setBookId(parts[1].trim());
                    context.setErrorMsg("请求解析成功");
                }
                outputQueue.put(context);
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            System.err.println("BorrowRequestParserFilter中断");
        }
    }
}
